package com.dengqi.mymodule.activity.loader.contacts;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;

import java.lang.ref.WeakReference;

import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;

/**
 * Created by dell on 2019/5/7
 */
public class ContactsCollection implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int LOADER_ID = 1;
    private WeakReference<Context> mContext;
    private LoaderManager mLoaderManager;
    private ContactsCollection.ContactsCallbacks mCallbacks;

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        //指定获取_id和display_name两列数据，display_name即为姓名
        String[] projection = new String[]{
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        CursorLoader loader = new CursorLoader(
                mContext.get(),
                ContactsContract.Contacts.CONTENT_URI,
                projection,
                null,
                null,
                null
        );
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
        Context context = mContext.get();
        mCallbacks.onContactsLoad(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        Context context = mContext.get();
        mCallbacks.onContactsReset();
    }

    public void init(FragmentActivity activity, ContactsCollection.ContactsCallbacks callbacks) {
        mContext = new WeakReference<Context>(activity);
        mLoaderManager = LoaderManager.getInstance(activity);
        mCallbacks = callbacks;
        mLoaderManager.initLoader(LOADER_ID, null, this);
    }

    public void destroyLoader(){
        mLoaderManager.destroyLoader(LOADER_ID);
    }

    public interface ContactsCallbacks {
        void onContactsLoad(Cursor cursor);
        void onContactsReset();
    }
}